package iot.wlink.service.impl;

import com.alibaba.fastjson.JSONObject;
import iot.wlink.bean.entity.DeviceTemplate;
import iot.wlink.bean.vo.DeviceTemplateVo;
import iot.wlink.bean.vo.ScriptCodecVo;
import iot.wlink.mapper.DeviceTemplateMapper;
import iot.wlink.network.devices.model.DeviceModel;
import iot.wlink.service.DeviceTemplateService;
import iot.wlink.utils.R;
import iot.wlink.utils.SnowFlakeUtil;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import java.util.Date;
import java.util.GregorianCalendar;

/**
 * @author : willian fu
 * @date : 2021/9/16
 */
@Slf4j
@Service
public class DeviceTemplateServiceImpl implements DeviceTemplateService {

    @Autowired
    private DeviceTemplateMapper templateMapper;

    @Override
    public Object getTemplateList() {
        return R.ok(templateMapper.selectTemplateList());
    }

    @Override
    public Object getTemplatesDetail(Long tid) {
        return R.ok(templateMapper.selectById(tid));
    }

    @Override
    public Object createTemplate(DeviceTemplateVo templateVo) {
        Date time = GregorianCalendar.getInstance().getTime();
        templateMapper.insert(DeviceTemplate.builder()
                .tid(SnowFlakeUtil.getInstance().nextId(false))
                .name(templateVo.getName())
                .avatar(templateVo.getAvatar())
                .networkType(templateVo.getNetworkType())
                .protocol(templateVo.getProtocol())
                .status(templateVo.getStatus())
                .deviceType(templateVo.getDeviceType())
                .created(time).updated(time).build());
        log.info("用户创建模板[{}]", templateVo.getName());
        return R.ok("创建模板 " + templateVo.getName() + " 成功");
    }

    @Override
    public Object delTemplate(Integer tid) {
        return null;
    }

    @Override
    public Object putTemplateStatus(Integer tid, Integer status) {
        return null;
    }

    @Override
    public Object setDataScriptCodec(ScriptCodecVo codec) {
        templateMapper.updateById(DeviceTemplate.builder()
                .tid(codec.getTid())
                .codecType(codec.getScriptType())
                .codecScript(codec.getCodeContent())
                .build());
        return R.ok("设置脚本解析成功");
    }

    @Override
    public Object setThingsModel(DeviceModel model) {
        templateMapper.updateById(DeviceTemplate.builder()
                .tid(model.getTid())
                .model(JSONObject.toJSONString(model))
                .build());
        return R.ok("设置物模型成功");
    }
}
